package com.thh.search;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.net.InetAddress;

/**
 * 查询： 高亮搜索
 */
public class App13_HighLight {

    //定义客户端
    TransportClient client;

    /*
    文档搜索： 分页搜索
     */
    @Test
    public void test1() throws Exception  {

        //查询条件
        QueryBuilder queryBuilder = QueryBuilders.queryStringQuery("java");
        //搜索
        search(queryBuilder,1,2,"price","asc");
    }

    /**
     * 分页搜索方法
     * @param queryBuilder  查询条件
     * @param pageNo       当前页
     * @param pageSize     页大小
     */
    private void search(QueryBuilder queryBuilder,int pageNo, int pageSize,String fieldName, String sort){

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color=\"#CC0000\">"); //前置标签
        highlightBuilder.field("bookname");
        highlightBuilder.field("bookdesc");
        highlightBuilder.postTags("</font>");//后置标签


        //执行查询
        SearchResponse searchResponse = client.prepareSearch("xiaofeifei_index") //从哪个索引找
                .setTypes("book")//从哪个类型中找
                .setQuery(queryBuilder) //查询条件
                .setFrom( (pageNo-1)*pageSize )  //开始记录索引  =  （当前页-1） * 页大小
                .setSize(pageSize) //页大小
                .addSort(fieldName, ("asc".equals(sort)? SortOrder.ASC : SortOrder.DESC))  //参数一：field； 参数二：排序规则
                .highlighter(highlightBuilder)
                .get();//执行
        //获取命中文档
        SearchHits hits = searchResponse.getHits();
        //总记录数
        System.out.println("命中文档数："+hits.getTotalHits());
        //获取文档
        SearchHit[] hitsHits = hits.getHits();

        //迭代获取数据
        for (SearchHit h : hitsHits) {
            System.out.println("id = "+h.getSourceAsMap().get("id"));
            System.out.println("price = "+h.getSourceAsMap().get("price"));
            System.out.println("pic = "+h.getSourceAsMap().get("pic"));
            System.out.println("bookname = "+h.getHighlightFields().get("bookname").getFragments()[0]); //获取高亮后的Field
            System.out.println("bookdesc = "+h.getHighlightFields().get("bookdesc").getFragments()[0]); //获取高亮后的Field
            System.out.println("========================================");
            System.out.println("");
        }

    }


    //初始化
    @Before
    public void init() throws Exception {
        //1、创建一个Settings对象，相当于一个配置信息。主要配置集群的名称。 cluster.name配置集群名称
        Settings settings = Settings.builder().put("cluster.name","elasticsearch").build();
        //2、创建一个客户端client对象。
        client = new PreBuiltTransportClient(settings);
        //3、使用client对象创建一个索引库。
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"),9300));
    }

    //释放资源
    @After
    public void close(){
        //4、关闭client对象。
        client.close();
    }
}
